package io.dbw.modules.business.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.dbw.common.utils.Constant;
import io.dbw.common.utils.PageUtils;
import io.dbw.common.utils.Query;
import io.dbw.modules.business.dao.SysBooksDao;
import io.dbw.modules.business.dao.SysBorrowDao;
import io.dbw.modules.business.entity.SysBorrowEntity;
import io.dbw.modules.business.entity.SysBorrowEntity;
import io.dbw.modules.business.service.SysBooksService;
import io.dbw.modules.business.service.SysBorrowService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Map;


@Service("sysBorrowService")
public class SysBorrowServiceImpl extends ServiceImpl<SysBorrowDao, SysBorrowEntity> implements SysBorrowService {
    @Autowired
    private SysBooksDao sysBooksDao;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SysBorrowEntity> page = this.page(
                new Query<SysBorrowEntity>().getPage(params),
                new QueryWrapper<SysBorrowEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveSysBorrow(SysBorrowEntity sysBorrow) {
        boolean save = this.save(sysBorrow);
        if(save){
            sysBooksDao.updateBooksStockReduce(sysBorrow.getBookId(),1);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateSysBorrow(SysBorrowEntity sysBorrow) {
        boolean update = this.update(Wrappers.<SysBorrowEntity>lambdaUpdate()
                .set(SysBorrowEntity::getStillFlag, Constant.SYSTEM_COMMON_Y)
                .eq(SysBorrowEntity::getBookId, sysBorrow.getBookId())
                .eq(SysBorrowEntity::getUserId, sysBorrow.getUserId())
                .eq(SysBorrowEntity::getStillFlag, Constant.SYSTEM_COMMON_N));
        if(update){
            sysBooksDao.updateBooksStockAdd(sysBorrow.getBookId(),1);
        }
    }
}